import axios from "axios";
import {Message, MessageBox} from "element-ui";

const service = axios.create({
    //baseURL: 'http://localhost:8080',
    timeout: 10000
})

// 请求拦截器
service.interceptors.request.use(
    config => {
        // TODO ...
        const jwt = localStorage.getItem('Authorization');
        if (jwt) {
            config.headers['Authorization'] = jwt;
        }
        return config;
    },
    error => {
        console.log(error);
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    response => {
        const res = response.data;
        if (res.state === 20000) {
            return res;
        }
        if (res.state === 40100) {
            MessageBox.confirm('登录过期，请重新登录', '提示', {
                type: 'warning',
                confirmButtonText: '重新登录'
            }).then(() => {
                // TODO ...
                localStorage.removeItem('_token');
                location.reload();
            });
        } else {
            Message({
                type: 'error',
                message: res.message,
                duration: 4 * 1000
            });
        }
        return Promise.reject(new Error(res.message || 'Error'));
    },
    error => {
        Message({
            type: 'error',
            message: error.message || 'Error',
            duration: 4 * 1000
        });
        return Promise.reject(error);
    }
);

export default service;
